package com.stedu.mall.userservice.controller;

import com.stedu.mall.common.bean.Addr;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.MallException;
import com.stedu.mall.common.service.AddrService;
import com.stedu.mall.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/addr")
public class AddrController {
    @Autowired
    private AddrService addrService;
    //添加
    @PostMapping
    public RespBean insert(@RequestBody Addr addr, @RequestHeader("token") String token) throws MallException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        addr.setUserId(userId);

        if (addrService.insert(addr)) {
            return RespBean.ok("添加成功");
        }
        return RespBean.error("添加失败");
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id, @RequestHeader("token") String token) throws MallException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if (!addrService.delete(id, userId)) {
            return RespBean.ok("删除失败");
        }

        return RespBean.ok("删除成功");
    }
    //修改
    @PutMapping
    public RespBean update(@RequestBody Addr addr, @RequestHeader("token") String token) throws MallException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if (addrService.update(addr, userId)) {
            return RespBean.ok("修改成功");
        }
        return RespBean.error("修改失败");
    }
    @GetMapping("/{addrId}")
    //根据商品id和用户id查询收藏
    public RespBean selectByGoodIdAndUserId(@PathVariable("addrId") Integer addrId) {

        Addr addr = addrService.selectById(addrId);

        return RespBean.ok("",addr);
    }
    //查询当前用户所有的地址
    @GetMapping
    public RespBean selectByUser (@RequestHeader("token") String token){
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer)map.get("id");
        Addr condition = new Addr();
        condition.setUserId(userId);

        List<Addr> list = addrService.selectByCondition(condition);

        return RespBean.ok("",list);
    }
}
